package com.salon.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.salon.common.exception.CustomException;
import com.salon.common.http.response.PageResult;
import com.salon.common.utils.Constant;
import com.salon.common.utils.Query;
import com.salon.modules.sys.entity.SysUserEntity;
import com.salon.modules.sys.mapper.SysUserMapper;
import com.salon.modules.sys.service.ISysRoleService;
import com.salon.modules.sys.service.ISysUserRoleService;
import com.salon.modules.sys.service.ISysUserService;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Resource;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 系统用户
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements
        ISysUserService {

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private ISysRoleService sysRoleService;

    @Override
    public PageResult<SysUserEntity> listByPage(Map<String, Object> params) {
        IPage<SysUserEntity> pageParams = new Query<SysUserEntity>().getPage(params);
        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        String username = (String) params.get("username");
        Long createUserId = (Long) params.get("createUserId");
        queryWrapper.like(StringUtils.isNotBlank(username), SysUserEntity::getUsername, username);
        queryWrapper.eq(Objects.nonNull(createUserId), SysUserEntity::getCreateUserId, createUserId);
        IPage<SysUserEntity> page = this.page(pageParams, queryWrapper);
        return new PageResult<>(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords());
    }

    @Override
    public List<Long> listMenuIdsByUserId(Long userId) {
        return baseMapper.listMenuIdsByUserId(userId);
    }

    @Override
    public SysUserEntity getUserInfoByName(String username) {
        return baseMapper.getUserInfoByName(username);
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user) {
        user.setCreateTime(new Date());
        // sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        this.save(user);
        // 检查角色是否越权
        checkRole(user);
        // 保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        this.updateById(user);
        // 检查角色是否越权
        checkRole(user);
        // 保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserEntity::getUserId, userId).eq(SysUserEntity::getPassword, password);
        return this.update(userEntity, queryWrapper);
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        // 如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }
        // 查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.listRoleIdByUserId(user.getCreateUserId());
        // 判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new CustomException("新增用户所选角色，不是本人创建");
        }
    }

}
